#include "ShellBase.h"
ShellBase::ShellBase(QObject *parent)
    : QObject(parent){
}
ShellBase::~ShellBase() {
}

void ShellBase::shell(QObject *target) {
    resetTarget("",target);
}
void ShellBase::shell(const TargetMap &target){
    for (auto iter=target.begin(); iter!=target.end(); iter++) {
        resetTarget(iter.key(),iter.value());
    }
}

void ShellBase::resetTarget(const QString &name, QObject *target) {
    if (_target.contains(name) && _target[name] == target) {
		return;
	}

    if (_target.contains(name)) {
        disconnect(_target[name], &QObject::destroyed, this, &ShellBase::onTargetDeleted);
        uninstallTarget(name,_target[name]);
    }

    if (nullptr == target) {
        _target.remove(name);
	}
    else{
        _target[name] = target;
        connect(_target[name], &QObject::destroyed, this, &ShellBase::onTargetDeleted);
        installTarget(name,target);
    }
}
QObject* ShellBase::target(const QString &name) {
    return _target.value(name,nullptr);
}
template<class T>
T* ShellBase::ttarget(const QString &name){
    return qobject_cast<T*>(target(name));
}

void ShellBase::onTargetDeleted(QObject *object) {
    if(!_target.values().contains(object)){
        return;
    }
    _target.remove(_target.key(object));
}
